/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.opengoofy.index12306.biz.ticketservice.config;

import cn.hippo4j.common.executor.support.BlockingQueueTypeEnum;
import cn.hippo4j.core.executor.DynamicThreadPool;
import cn.hippo4j.core.executor.support.ThreadPoolBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Hippo4j 动态线程池配置
 * <a href="https://github.com/opengoofy/hippo4j">异步线程池框架，支持线程池动态变更&监控&报警</a>
 * 公众号：马丁玩编程，回复：加群，添加马哥微信（备注：12306）获取项目资料
 */
@Configuration
public class Hippo4jThreadPoolConfiguration {

    /**
     * 分配一个用户购买不同类型车票的线程池
     * 该线程池用于处理用户购买不同类型车票的请求，通过动态线程池管理器进行管理
     * 详见：[线程池参数如何设置](https://nageoffer.com/12306/question)
     */
    @Bean
    @DynamicThreadPool
    public ThreadPoolExecutor selectSeatThreadPoolExecutor() {
        // 定义线程池的标识
        String threadPoolId = "select-seat-thread-pool-executor";
        // 构建线程池配置，从核心参数到拒绝策略进行全面配置
        return ThreadPoolBuilder.builder()
                .threadPoolId(threadPoolId) // 设置线程池标识，用于区分和管理不同的线程池
                .threadFactory(threadPoolId) // 设置线程工厂，用于创建带有命名空间的线程
                .workQueue(BlockingQueueTypeEnum.SYNCHRONOUS_QUEUE) // 设置工作队列为同步队列，不存储任务
                .corePoolSize(24) // 设置核心线程数，根据预期并发量调整
                .maximumPoolSize(36) // 设置最大线程数，允许在高并发时扩张
                .allowCoreThreadTimeOut(true) // 允许核心线程超时，空闲时减少线程数
                .keepAliveTime(60, TimeUnit.MINUTES) // 设置非核心线程的存活时间，减少资源消耗
                .rejected(new ThreadPoolExecutor.CallerRunsPolicy()) // 设置拒绝策略，由调用者处理无法执行的任务
                .dynamicPool() // 动态线程池，支持通过配置中心动态调整线程池参数
                .build(); // 构建线程池实例
    }
}
